/**
 * \ * @Title: ApplicationUtil.java
 *
 * @author 7828wc
 * @date 2015年9月8日 下午5:12:04
 */
package com.shanghaionstar.utils;


import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.onstar.cn.auth.userProfile.Account;
import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.auth.userProfile.ServiceEntitlement;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.auth.userProfile.VehicleUnitFeature;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.vehicle.response.features.CommandDataEntity;
import com.onstar.cn.vehicle.response.features.CommandEntity;
import com.onstar.cn.vehicle.response.features.ServiceFeatureCommandEntity;
import com.onstar.cn.vehicle.response.features.ServiceFeatureEntity;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/**
 * @author 7828wc
 * @ClassName: ApplicationUtil.java
 * @Description: 保存应用全局数据
 * @date 2015年9月8日
 */
public class ApplicationUtil {

    public static final int ALERT_DURATION_DEF = 30;
    private Subscriber subscriber;

    /**
     * 当前车辆信息
     */
    private Vehicle currentVehicle;

    /**
     * 闪灯鸣笛duration 时间
     */
    private int alertDuration = -1;

    boolean isLogin;

    public boolean isCommanding = false;

    public void controlCommand(Context context) {
        if (isCommanding) {
            AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
                    context.getString(R.string.service_inProcess_alert));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isCommanding = false;
                }
            }, 10000);
        }
    }


    public void clearData() {
        isLogin = false;
        subscriber = null;
        currentVehicle = null;
        supportedDiagnostic = null;
        currentAccount = null;
        serviceItems = null;
        serviceEntitlement = null;
        token = "";
    }

    public ServiceItem getServiceItemByName(String name) {
        List<ServiceItem> serviceItems = ApplicationUtil.getInstance().getServiceItems();
        if (serviceItems != null && !serviceItems.isEmpty()) {
            for (ServiceItem item : serviceItems) {
                if (item.getServiceName().equalsIgnoreCase(name)) {
                    return item;
                }
            }
        }
        return null;
    }

    public List<ServiceItem> getServiceItems() {
        return serviceItems;
    }

    public void setServiceItems(List<ServiceItem> serviceItems) {
        this.serviceItems = serviceItems;
    }

    private List<ServiceItem> serviceItems;

    /**
     * 车辆刷新请求数组
     */
    private String[] supportedDiagnostic;

    /**
     * 当前账户信息
     */
    private Account currentAccount;

    private List<ServiceEntitlement> serviceEntitlement;

    /**
     * MIG 验证token
     */
    private String token;

    public Account getCurrentAccount() {
        return currentAccount;
    }

    public void setCurrentAccount(Account currentAccount) {
        this.currentAccount = currentAccount;
    }


    private static class LazyHolder {
        private static final ApplicationUtil INSTANCE = new ApplicationUtil();
    }

    private ApplicationUtil() {
    }

    public static final ApplicationUtil getInstance() {
        return LazyHolder.INSTANCE;
    }

    public void updateUserProfile(Subscriber subscriber) {
        this.subscriber = subscriber;
        updateCurrentInfo(subscriber);
    }

    public void updateCurrentInfo(Subscriber subscriber) {
        if (subscriber != null) {
            if (!CommonUtil.isNull(subscriber.getDefaultAccountID()) && !CommonUtil.isNull(subscriber.getAccounts()) && subscriber.getAccounts().size() > 0) {
                for (com.onstar.cn.auth.userProfile.Account account : subscriber.getAccounts()) {
                    if (account.getAccountID().equalsIgnoreCase(subscriber.getDefaultAccountID())) {
                        setCurrentAccount(account);
                        if (!CommonUtil.isNull(account.getVehicles()) && account.getVehicles().size() > 0) {
                            for (Vehicle vehicle : account.getVehicles()) {
                                if (account.getDefaultVin().equalsIgnoreCase(vehicle.getVin())) {
                                    setCurrentVehicle(vehicle);
                                    break;
                                }
                            }
                            //如果没有找到Default的车辆信息，默认将车辆列表中第一辆车的信息
                            if (CommonUtil.isNull(getCurrentVehicle())) {
                                setCurrentVehicle(account.getVehicles().get(0));
                            }
                        }
                        break;
                    }
                }
                //如果没有找到Default的Account信息，默认将Account 列表第一个Account的信息
                if (CommonUtil.isNull(getCurrentAccount())) {
                    setCurrentAccount(subscriber.getAccounts().get(0));
                }
            } else {
                //如果没有找到Default的Account信息，默认将Account 列表第一个Account的信息
                if (!CommonUtil.isNull(subscriber.getAccounts()) && subscriber.getAccounts().size() > 0) {
                    setCurrentAccount(subscriber.getAccounts().get(0));
                    //如果没有找到Default的车辆信息，默认将车辆列表中第一辆车的信息
                    setCurrentVehicle(subscriber.getAccounts().get(0).getVehicles().get(0));
                }
            }
        }

    }


    public Vehicle getCurrentVehicle() {
        return currentVehicle;
    }

    public void setCurrentVehicle(Vehicle currentVehicle) {
        this.currentVehicle = currentVehicle;
    }


    public boolean isD2jbi() {
        return currentVehicle == null ? false : currentVehicle.getIsD2jbi();
    }

    public boolean isCurrentInfo3Vehicle() {
        return currentVehicle == null ? false : currentVehicle.isInfo3();
    }

    public String getSubscriberID() {
        return subscriber == null ? "" : subscriber.getSubscriberID();
    }

    public boolean isInfo3Flag() {
        return subscriber == null ? false : subscriber.isInfo3Flag();
    }

    public List<VehicleUnitFeature> getVehicleUnitFeatures() {
        return vehicleUnitFeatures;
    }

    public List<ServiceEntitlement> getServiceEntitlement() {
        if (currentVehicle != null)
            return currentVehicle.getServiceEntitlement();
        return null;
    }

    public boolean isVolt() {
        String model = getModelDesc();
        if (TextUtils.isEmpty(model))
            return false;
        return model.contains("volt") || model.contains("沃蓝达");
    }

    public boolean isBuick() {
        String model = getModelDesc();
        if (TextUtils.isEmpty(model))
            return false;
        return model.contains("buick") || model.contains(OnstarApplication.getApplication().getString(R.string.assistant_buick));
    }

    public String getModelDesc() {
        if (currentVehicle == null)
            return "";
        String model = currentVehicle.getModelDesc();
        if (TextUtils.isEmpty(model))
            return "";
        return model.toLowerCase(Locale.CHINA);
    }

    public boolean isBBWC() {
        if (currentVehicle == null)
            return false;
        return currentVehicle.isBbwc();
    }

    public boolean isFmvOpt() {
        if (currentVehicle == null)
            return false;
        return currentVehicle.isFmvOpt();
    }

    public boolean isRemoteControlOpt() {
        if (currentVehicle == null)
            return false;
        return currentVehicle.isRemoteControlOpt();
    }

    public String getLoginRole() {
        if (subscriber != null)
            return subscriber.getRole();
        return "";
    }

    public String getIdpID() {
        if (subscriber != null)
            return subscriber.getIdpID();
        return "";
    }

    public String getPhoneNumber() {
        if (subscriber != null)
            return subscriber.getPhoneNumber();
        return "";
    }

    public String getEmail() {
        if (subscriber != null)
            return subscriber.getEmail();
        return "";
    }

    public Set<String> getVehicleIds() {
        if (subscriber != null)
            return subscriber.getVehicleIds();
        return null;
    }
//
//    private String firstName;
//    private boolean isBuick;
//    private boolean isVolt;

    public void setFirstName(String firstName) {
        if (subscriber != null)
            subscriber.setFirstName(firstName);
    }

    public void setLastName(String lastName) {
        if (subscriber != null)
            subscriber.setLastName(lastName);
    }

    public String getFirstName() {
        if (subscriber != null)
            return subscriber.getFirstName();
        return "";
    }

    public String getLastName() {
        if (subscriber != null)
            return subscriber.getLastName();
        return "";
    }

    public boolean isChangingVehicleAllowed() {
        if (subscriber != null)
            return subscriber.isChangingVehicleAllowed();
        return false;
    }

    public boolean isExpiredSubscriber() {
        if (subscriber != null)
            return subscriber.isExpiredSubscriber();
        return false;
    }


    public boolean isGen10() {
        if (currentVehicle != null)
            return currentVehicle.isGen10();
        return false;
    }


    public void setAlertDuration(int duration) {
        this.alertDuration = duration;
    }

    public int getAlertDuration() {
        return alertDuration;
    }


    public String getVin() {
        return currentVehicle == null ? "" : currentVehicle.getVin();
    }


    /**
     * 获取当前车辆make,model信息
     *
     * @return
     */
    public String getCarInfo() {
        return currentVehicle == null ? "" : currentVehicle.getMakeDesc() + " " + currentVehicle.getModelDesc();
    }

    public String getAccountId() {
        return currentAccount == null ? "" : currentAccount.getAccountID();
    }


    public void setLogin(boolean isLogin) {
        this.isLogin = isLogin;
    }

    public boolean isLogin() {
        return isLogin;
    }


    public String getToken() {
        return TextUtils.isEmpty(token) ? FinalConstants.HTTP_AUTHORIZATION : token;
    }

    public void setToken(String token) {
        this.token = token;
    }


    public void updateToken(String tokenType, String token) {
        if (!CommonUtil.isNull(tokenType)) {
            setToken(tokenType + " " + token);
        } else {
            setToken(token);
        }
    }


    /**
     * 是否自动登录，如果正在登录该值会为true，这是需弹出Dialog提示“正在连接你的车”
     */
    private boolean isAutoLoging = false;


    public boolean isAutoLogings() {
        return isAutoLoging;
    }

    public void setAutoLoging(boolean isAutoLoging) {
        this.isAutoLoging = isAutoLoging;
    }


    public void setPin(boolean pin) {
        isPin = pin;
    }

    private boolean isPin;

    public boolean isPin() {
        return isPin;
    }

    public String[] getSupportedDiagnostic() {
        return supportedDiagnostic;
    }

    public void setSupportedDiagnostic(String[] supportedDiagnostic) {
        this.supportedDiagnostic = supportedDiagnostic;
    }


    public void setVehicleUnitFeatures(List<VehicleUnitFeature> vehicleUnitFeatures) {
        this.vehicleUnitFeatures = vehicleUnitFeatures;
    }

    List<VehicleUnitFeature> vehicleUnitFeatures;


    public void updateVehicleUnitFeatures(ServiceFeatureCommandEntity entity) {
        List<VehicleUnitFeature> vehicleUnitFeatures = new ArrayList<VehicleUnitFeature>();
        ServiceFeatureEntity serviceFeatureEntity = entity.getCommands();
        List<CommandEntity> commandEnties = serviceFeatureEntity.getCommand();
        for (CommandEntity commandEntity : commandEnties) {
            VehicleUnitFeature feature = new VehicleUnitFeature();
            feature.setFeatureName(commandEntity.getName());
            if (FeatureEnum.DIAGNOSTICS.value().equals(commandEntity.getName())) {
                CommandDataEntity dataEntity = commandEntity.getCommandData();
                if (dataEntity.getSupportedDiagnostics() != null) {
                    String[] supportedDiagnostic = dataEntity.getSupportedDiagnostics().getSupportedDiagnostic();
                    this.supportedDiagnostic = supportedDiagnostic;
                }
            } else {
                feature.setValue("true");
            }
            vehicleUnitFeatures.add(feature);
        }
        this.vehicleUnitFeatures = vehicleUnitFeatures;
    }


    public void setServiceEntitlement(List<ServiceEntitlement> serviceEntitlement) {
        this.serviceEntitlement = serviceEntitlement;
    }


    public void updateServiceEntitlement(List<ServiceEntitlement> serviceEntitlement) {
        this.serviceEntitlement = serviceEntitlement;
    }


    public boolean getSupportedDiagnostic(String diagnosticName) {
        if (CommonUtil.isNull(diagnosticName)) {
            return false;
        }
        if (supportedDiagnostic != null && supportedDiagnostic.length > 0) {
            for (String diagnostic : supportedDiagnostic) {
                if (diagnostic.equalsIgnoreCase(diagnosticName)) {
                    return true;
                }
            }
        }
        return false;
    }


    public String getMobile() {
        return subscriber == null ? "" : subscriber.getPhoneNumber();

    }

    public static boolean isActivityFront() {
        return OnstarApplication.getApplication().isActivityFront();
    }


    /**
     * 判断是否是phev车
     * <p/>
     * 新规则：
     * <p/>
     * 1、    满足PHEV车型（veh_manuf_year = 2016  and  veh_model = 'K5'  and veh_make = 'L' and veh_manuf = 'G'）
     * 以及（veh_manuf_year = 2017  and  veh_model = 'R1'  and veh_make = 'L' and veh_manuf = 'G'）
     * 2、     满足enrlmn_complt_status_cd为1
     * 3、     满足veh_status_cd为VSACTIVE
     * 4、     满足Unit config完成
     * 5、     状态不是opt in的
     * <p/>
     * 影响到的业务有：
     * 1，PHEV data refersh
     * 2，PHEV充电模式功能
     * 3，PHEV出发时间设置功能
     * 4，PHEV充电通知功能
     * 5，MA7.0中首页的驾驶评分入口PHEV车辆隐藏
     * 6，PHEV充电站功能
     */
    public boolean isPhev() {
        return currentVehicle == null ? false : currentVehicle.isPhev();
    }

    public boolean isAuthorized() {
        return subscriber == null ? false : subscriber.isCarSharingFlag();
    }

    public void setAuthorized(boolean carFlag) {
        if (subscriber != null)
            subscriber.setCarSharingFlag(carFlag);
    }


}
